package com.zis.aspect;

import com.alibaba.fastjson.JSONObject;
import com.zis.auth.service.ISercretInter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后端接口校验拦截
 * Create by wangshen 2017/12/26
 */
@Aspect
@Configuration
public class VerifyTokenAspect {

    private static final Logger logger = LoggerFactory.getLogger(VerifyTokenAspect.class);

    @Autowired
    private ISercretInter sercretInter;

    /**
     * 声明切入点，只处理controller
     */
    @Pointcut("execution(* com.zis.*.controller.*.*(..)) && !execution(* com.zis.auth.controller.*.*(..))")
    private void pointCutMethod() {
    }

    //声明前置通知
    @Before("pointCutMethod()")
    public void doBefore() {
    }

    //声明后置通知
    @AfterReturning(pointcut = "pointCutMethod()", returning = "result")
    public void doAfterReturning(String result) {
        logger.info(" --- 响应结果 --> " + result);
    }

    //声明例外通知
    @AfterThrowing(pointcut = "pointCutMethod()", throwing = "e")
    public void doAfterThrowing(Exception e) {
        logger.error(" --- 异常信息 --> "+e.getMessage(),new Throwable(e));
    }

    //声明最终通知
    @After("pointCutMethod()")
    public void doAfter() {
    }

    @Around("pointCutMethod()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        logger.debug(" --- request start params --> url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);
        HttpServletResponse response = sra.getResponse();
        String authorization = request.getHeader("Authorization");
        //排除部分不需要校验的URL
        if(authorization==null||authorization.equals("")){
            logger.debug(" --- 未进行登录授权");
            response.setCharacterEncoding("utf-8");
            response.setStatus(403);//-1去登录
            return null;
        }
        String authInfo = sercretInter.getClient(authorization);
        JSONObject authJSON = JSONObject.parseObject(authInfo);
        if(!authJSON.get("code").equals(0)){
            logger.debug(" --- 登陆信息失效");
            response.setCharacterEncoding("utf-8");
            response.setStatus(403);//-1去登录
            return null;
        }
        JSONObject userInfo = authJSON.getJSONObject("respData");
        String code = userInfo.get("userCode").toString();
        request.setAttribute("code", code);
        Object o = pjp.proceed();
        return o;
    }
}
